package com.xm.xm.undercover.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.xm.xm.undercover.R
import kotlinx.android.synthetic.main.activity_room.*
import android.content.ComponentName
import android.os.IBinder
import android.content.ServiceConnection
import android.content.IntentFilter
import android.content.BroadcastReceiver
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.xm.xm.undercover.bean.GetMessage
import com.xm.xm.undercover.bean.Msg
import com.xm.xm.undercover.bean.StartInfo
import com.xm.xm.undercover.service.CreateAGameService
import com.xm.xm.undercover.service.JWebSocketClientService
import com.xm.xm.undercover.utils.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response




class RoomActivity : AppCompatActivity() {

    private val msgList = ArrayList<Msg>()
    private var adapter: MsgAdapter?=null

    companion object {
        val everyone = arrayOf(
            UserInfo.u1,
            UserInfo.u2,
            UserInfo.u3,
            UserInfo.u4,
            UserInfo.u5,
            UserInfo.u6,
            UserInfo.u7,
            UserInfo.u8
        )
    }


    lateinit var socketMessageReceiver: SocketMessageReceiver
    lateinit var bind: JWebSocketClientService.JWebSocketClientBinder
    var client : JWebSocketClient?=null

    private val connection = object : ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d("testActivity","start bind")
            bind = service as JWebSocketClientService.JWebSocketClientBinder
            val jClient = bind.getService()
            client = jClient.client
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)
        val layoutManager = LinearLayoutManager(this)
        ActivityCollector.addActivity(this)
        recyclerView.layoutManager = layoutManager
        adapter = MsgAdapter(msgList)
        recyclerView.adapter =adapter
        val roomId = intent.getStringExtra("roomId")
        roomIdText.text = "房间号：$roomId"
        Log.d("testActivity","in the room")

        val intent = Intent(this,JWebSocketClientService::class.java)
        startService(intent)
        bindService(intent,connection,Context.BIND_AUTO_CREATE)

        if (UserInfo.isRoomOwner){
            startBtn.isVisible = true
            startBtn.isClickable = true
            startBtn.isEnabled = true
        }

        val intentFilter = IntentFilter()
        intentFilter.addAction("com.xm.under.SOCKET")
        socketMessageReceiver = SocketMessageReceiver()
        registerReceiver(socketMessageReceiver,intentFilter)

        startBtn.setOnClickListener {
            startBtn.isClickable = false
            val xs = arrayOf(x1,x2,x3,x4,x5,x6,x7,x8)
            for (x in xs){
                x.isVisible = false
            }
            val users = arrayOf(userName1,userName2,userName3,userName4,userName5,userName6,userName7,userName8)
            val imgs = arrayOf(img1,img2,img3,img4,img5,img6,img7,img8)
            for (i in 0..7){
                if (!users[i].text.equals("")){
                    imgs[i].isClickable = true
                    imgs[i].isEnabled = true
                }
                else{
                    imgs[i].isClickable = false
                    imgs[i].isEnabled = false
                }
            }
            val createAGameService = ServiceCreator.create<CreateAGameService>()
            val startInfo = StartInfo(UserInfo.curUserId,UserInfo.curRoom)
            Log.d("thisActivity","msgmsg"+startInfo.owner + " "+startInfo.roomId)
            val ans_game = createAGameService.doCreateAGame(startInfo)
            val res_game = ans_game.enqueue(object :Callback<GetMessage>{
                override fun onFailure(call: Call<GetMessage>, t: Throwable) {
                }

                override fun onResponse(call: Call<GetMessage>, response: Response<GetMessage>) {
                    Log.d("thisActivity","create a game success")
                }
            })
        }
        val imgs = arrayOf(img1,img2,img3,img4,img5,img6,img7,img8)
        val votes = arrayOf(vote1,vote2,vote3,vote4,vote5,vote6,vote7,vote8)

        for (myImg in imgs) {
           myImg.setOnClickListener {
                for (curImg in imgs) {
                    curImg.isClickable = false
                    curImg.isEnabled = false
                }
               val myIndex = UserInfo.curUserIndex.toInt()
               votes[myIndex-1].text = ""+(imgs.indexOf(myImg)+1)
               votes[myIndex-1].isVisible = true
               val getMessage = GetMessage("2",UserInfo.curUserId,null,""+(imgs.indexOf(myImg)+1))
               val json = Gson().toJson(getMessage)
               client?.send(json)
               Log.d("testActivity",json)

            }
        }
        send.setOnClickListener {
            val text = editText.text
            val chat = Msg(text.toString(),UserInfo.curUserIndex)
            msgList.add(chat)
            adapter?.notifyItemInserted(msgList.size-1)
            recyclerView.scrollToPosition(msgList.size-1)
            val message = GetMessage("6",UserInfo.curUserIndex,UserInfo.curRoom,text.toString())
            val json = Gson().toJson(message)
            editText.text.clear()
            client?.send(json)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(socketMessageReceiver)
        ActivityCollector.removeActivity(this)
        UserInfo.isRoomOwner = false
        startBtn.isClickable = false
        startBtn.isEnabled = false
        startBtn.isVisible = false
    }


    inner class SocketMessageReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val message = intent.getStringExtra("message")
            doRead(context,message.toString())
//            Log.d("testActivity","socket message : $message")
//            val con = context as Activity
//            val imgtext = con.findViewById<ImageView>(R.id.img5)
//            imgtext.setImageResource(R.mipmap.tx5)
        }
    }

    fun doRead(context:Context,message:String){

        val gson = Gson()
        val info =  gson.fromJson(message,GetMessage::class.java)
        when (info.id){
            // 1 3 4 5 7  8 9 10
            "9" -> updateUserUI(context,info.mes)
            "1" -> getWords(context,info.mes)
            "7" -> updateIndex(context,info.mes)
            "3" -> updateVote(context,info.mes,info.to)
            "8" -> voteInfo(context,info.mes,info.from)
            "4" -> gameEnd(context,info.mes)
            "10" -> showChat(context,info.mes,info.from)
            "12" -> becomeOwner(context)
        }
    }

    private fun becomeOwner(context: Context) {
        val con = context as Activity
        val btn = con.findViewById<Button>(R.id.startBtn)
        btn.isEnabled = true
        btn.isClickable = true
        btn.isVisible = true
    }

    private fun showChat(context: Context, mes: String, from: String?) {
        var index = "0"
        if (from!=null){
            index = from
        }
        val chat = Msg(mes,index)
        msgList.add(chat)
        adapter?.notifyItemInserted(msgList.size-1)
        recyclerView.scrollToPosition(msgList.size-1)

    }

    private fun gameEnd(context: Context, mes: String) {
        val con = context as Activity
        con.findViewById<Button>(R.id.startBtn).isClickable = true
    }

    private fun voteInfo(context: Context, mes: String, from: String?) {
        // 展示每位玩家投票信息
        val con = context as Activity
        val votes = arrayOf(vote1,vote2,vote3,vote4,vote5,vote6,vote7,vote8)
        var index = from?.toInt()
        if (index == null){
            index = 0
        }
        votes[index].text = mes
        votes[index].isVisible = true
    }

    private fun updateVote(context: Context, mes: String,vote:String?) {
        // 展示本回合投票结果
        val con = context as Activity
        val xs = arrayOf<ImageView>(con.findViewById(R.id.x1),con.findViewById(R.id.x2),con.findViewById(R.id.x3),con.findViewById(R.id.x4),
            con.findViewById(R.id.x5),con.findViewById(R.id.x6),con.findViewById(R.id.x7),con.findViewById(R.id.x8))
        var index = vote?.toInt()
        if (index==null){
            index = 0
        }
        xs[index].isVisible = true
        // TODO
        // 展示投票是否正确  （聊天框显示）
        // 隐藏每位玩家的投票信息
        val votes = arrayOf<TextView>(con.findViewById(R.id.vote1),con.findViewById(R.id.vote2),con.findViewById(R.id.vote3),con.findViewById(R.id.vote4),
            con.findViewById(R.id.vote5),con.findViewById(R.id.vote6),con.findViewById(R.id.vote7),con.findViewById(R.id.vote8))
        for (vot in votes){
            vot.isVisible = false
        }


    }

    private fun updateIndex(context: Context, mes: String) {
        UserInfo.curUserIndex = mes
    }

    private fun getWords(context: Context, mes: String) {
        val con = context as Activity
        val wordsText = con.findViewById<TextView>(R.id.yourWords)
        wordsText.text = mes

    }

    private fun updateUserUI(context:Context,mes:String) {
        val userInfo = mes.split(";")
        for (str in userInfo){
            Log.d("testActivity",str)
            val strs = str.split(",")
            val userIndex = strs[0].toInt()-1
            val userName = strs[1]
            showUser(context,userIndex,userName)
        }
    }


    fun showUser(context: Context,index:Int,name:String){

        Log.d("testActivity","start show")

        Log.d("testActivity","start show2")
        val con = context as Activity

//        Log.d("testActivity","start show")
        val userNameText = arrayOf<TextView>(con.findViewById(R.id.userName1),con.findViewById(R.id.userName2),con.findViewById(R.id.userName3),
            con.findViewById(R.id.userName4),con.findViewById(R.id.userName5),con.findViewById(R.id.userName6),con.findViewById(R.id.userName7),con.findViewById(R.id.userName8))

        val userImg = arrayOf(R.mipmap.tx1,R.mipmap.tx2,R.mipmap.tx3,R.mipmap.tx4,R.mipmap.tx5,R.mipmap.tx6,R.mipmap.tx7,R.mipmap.tx8)
        val userImgText = arrayOf<ImageView>(con.findViewById(R.id.img1),con.findViewById(R.id.img2),con.findViewById(R.id.img3),
            con.findViewById(R.id.img4),con.findViewById(R.id.img5),con.findViewById(R.id.img6),con.findViewById(R.id.img7),con.findViewById(R.id.img8))
//        Log.d("testActivity","start show2")
        userImgText[index].setImageResource(userImg[index])
        userNameText[index].text = name
        everyone[index] = name
    }




    /**
     * 动态注册广播
     */
    private fun doRegisterReceiver() {
        val socketMessageReceiver = SocketMessageReceiver()
        val filter = IntentFilter("com.xm.undercover.socket")
        registerReceiver(socketMessageReceiver, filter)
    }

}
